// 通过rem拿到px
export function getPxFromRem(rem: number) {
  return rem * Number.parseFloat(getComputedStyle(document.documentElement).fontSize)
}

/**
 * 兼容移动端的复制文本函数
 * @param text 要复制的文本
 * @returns Promise<boolean> 复制是否成功
 */
export async function copyText(text: string): Promise<boolean> {
  const lang: any = getCurrentPageLang('system')

  try {
    // 优先使用现代 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      showNotify({ type: 'success', message: lang.copy_success })
      return true
    }
  } catch (error) {
    console.warn(
      'Clipboard API failed, falling back to fallback method:',
      error,
    )
  }

  // 降级方案：使用 document.execCommand
  try {
    const textArea = document.createElement('textarea')
    textArea.value = text

    // 设置样式，使其不可见
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    textArea.style.opacity = '0'
    textArea.style.pointerEvents = 'none'
    textArea.style.zIndex = '-1'

    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    document.execCommand('copy')
    document.body.removeChild(textArea)
    showNotify({ type: 'success', message: lang.copy_success })
    return true
  } catch (error) {
    console.error('Fallback copy method failed:', error)
    return false
  }
}

// 通用日期格式化：支持时间戳、Date、字符串。无效入参返回空字符串
export function formatDate(
  input: unknown,
  format: string = 'YYYY-MM-DD',
): string {
  if (input === null || input === undefined)
    return ''
  if (Array.isArray(input)) {
    input = input.join('-')
  }

  let date: Date | null = null

  // Helper to check valid Date
  const isValidDate = (d: Date) =>
    d instanceof Date && !Number.isNaN(d.getTime())

  if (input instanceof Date) {
    date = input
  } else if (typeof input === 'number') {
    // Detect seconds vs milliseconds
    const ms = Math.abs(input) < 1e12 ? input * 1000 : input
    date = new Date(ms)
  } else if (typeof input === 'string') {
    const trimmed = input.trim()
    if (trimmed === '')
      return ''

    // Numeric string -> timestamp
    if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
      const num = Number(trimmed)
      const ms = Math.abs(num) < 1e12 ? num * 1000 : num
      date = new Date(ms)
    } else {
      // Fallback to Date parsing
      date = new Date(trimmed)
    }
  } else {
    return ''
  }

  if (!date || !isValidDate(date))
    return ''

  const year = date.getFullYear()
  const month = date.getMonth() + 1 // 1-12
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()

  const pad2 = (n: number) => (n < 10 ? `0${n}` : String(n))

  // Replace tokens in one pass to avoid overlaps
  return format.replace(/YYYY|YY|MM|M|DD|D|HH|H|mm|m|ss|s/g, (token) => {
    switch (token) {
      case 'YYYY':
        return String(year)
      case 'YY':
        return String(year).slice(-2)
      case 'MM':
        return pad2(month)
      case 'M':
        return String(month)
      case 'DD':
        return pad2(day)
      case 'D':
        return String(day)
      case 'HH':
        return pad2(hours)
      case 'H':
        return String(hours)
      case 'mm':
        return pad2(minutes)
      case 'm':
        return String(minutes)
      case 'ss':
        return pad2(seconds)
      case 's':
        return String(seconds)
      default:
        return token
    }
  })
}

// 2位数，自动补零
export function pad2(n: string | number | undefined) {
  if (!n && n !== 0) {
    return ''
  }
  return String(n).padStart(2, '0')
}

export const apo: any = {}

export function initApo() {
  const userStore = useUserStore()
  const obj: any = {
    user: {
      currency_symbol: userStore.moneyUnit,
    },
    utils: {
      formateAmountWithSymbol(data: any) {
        return `${userStore.moneyUnit}${data}`
      },
      formatAmount(data: any) {
        return data
      },
      formatDate() {
        return 'YYYY-MM-DD HH:mm:ss'
      }
    },
    toast: {
      showToast(msg: string) {
        return showToast(msg)
      },
      showSuccess(msg: string) {
        return showSuccessToast(msg)
      },
      showFail(msg: string) {
        return showFailToast(msg)
      },
    },
    logger: {
      error(...args: any) {
        console.error(...args)
      },
    },
    config:{
      getCurrencyName() {
        return 'BRL'
      }
    },
    activity: {
      getHistoryList() {
        return
      },
      getActivityDetailInfo(activityType: number, callback: (error?: Error, data?: any) => void) {
        $fetch('https://api.ganha365.com/api/v1/activity/detailinfo', {
          method: 'POST',
          body: {
            activity_type: activityType,
            aid: 400001,
            is_auto: true,
          },
        }).then((res: any) => {
          if (res.data) {
            callback(undefined, res.data || {})
          } else {
            callback(res)
          }
        }).catch((err: any) => {
          callback(err)
        })
      },
      claimActivityReward(activityType: number, callback: (error?: Error, data?: any) => void, data?: any) {
        $fetch('https://api.ganha365.com/api/v1/activity/receive', {
          method: 'POST',
          body: {
            activity_type: activityType,
            aid: 400001,
            extension_params: JSON.stringify(data),
          },
        }).then((res: any) => {
          if (res.data) {
            callback(undefined, res.data || {})
          } else {
            callback(res)
          }
        }).catch((err: any) => {
          callback(err)
        })
      },
    },
  }
  Object.keys(obj).forEach((key: string) => {
    apo[key] = obj[key]
  })
}
